/**
 * 平台服务模块
 * 负责管理各个社交媒体平台的配置信息
 */
import * as sqlite3 from 'sqlite3';
import * as path from 'path';
import * as fs from 'fs';

interface Platform {
  id: string;
  name: string;
  displayName: string;
  icon: string;
  enabled: boolean;
  config: any;
}

export class PlatformService {
  private db: sqlite3.Database;

  constructor() {
    try {
      // 确保数据库目录存在
      const dataDir = path.join(__dirname, '../../../data');
      if (!fs.existsSync(dataDir)) {
        fs.mkdirSync(dataDir, { recursive: true });
        console.log('数据库目录已创建:', dataDir);
      }
      
      const dbPath = path.join(dataDir, 'app.db');
      console.log('PlatformService 正在连接数据库:', dbPath);
      
      this.db = new sqlite3.Database(dbPath, (err) => {
        if (err) {
          console.error('PlatformService 数据库连接失败:', err.message);
          throw err;
        } else {
          console.log('PlatformService 数据库连接成功');
        }
      });
      
      this.initDatabase();
    } catch (error) {
      console.error('PlatformService 初始化失败:', error);
      throw error;
    }
  }

  /**
   * 初始化数据库表结构
   */
  private initDatabase() {
    this.db.run(`
      CREATE TABLE IF NOT EXISTS platforms (
        id TEXT PRIMARY KEY,
        name TEXT NOT NULL,
        displayName TEXT NOT NULL,
        icon TEXT,
        enabled BOOLEAN DEFAULT 1,
        config TEXT,
        createdAt DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `, (err) => {
      if (err) {
        console.error('创建platforms表失败:', err.message);
      } else {
        console.log('platforms表初始化成功');
        // 初始化默认平台
        this.initDefaultPlatforms();
      }
    });
  }

  /**
   * 初始化默认平台配置
   */
  private async initDefaultPlatforms() {
    console.log('正在初始化默认平台配置...');
    const defaultPlatforms = [
      {
        id: 'douyin',
        name: 'douyin',
        displayName: '抖音',
        icon: '🎵',
        enabled: true,
        config: JSON.stringify({
          baseUrl: 'https://www.douyin.com',
          uploadEndpoint: '/creator/upload',
          maxFileSize: 2 * 1024 * 1024 * 1024, // 2GB
          supportedFormats: ['mp4', 'mov', 'avi']
        })
      },
      {
        id: 'bilibili',
        name: 'bilibili',
        displayName: '哔哩哔哩',
        icon: '📺',
        enabled: true,
        config: JSON.stringify({
          baseUrl: 'https://www.bilibili.com',
          uploadEndpoint: '/video/upload',
          maxFileSize: 8 * 1024 * 1024 * 1024, // 8GB
          supportedFormats: ['mp4', 'flv', 'avi']
        })
      },
      {
        id: 'xiaohongshu',
        name: 'xiaohongshu',
        displayName: '小红书',
        icon: '📒',
        enabled: true,
        config: JSON.stringify({
          baseUrl: 'https://www.xiaohongshu.com',
          uploadEndpoint: '/api/upload/video',
          maxFileSize: 1 * 1024 * 1024 * 1024, // 1GB
          supportedFormats: ['mp4', 'mov']
        })
      }
    ];

    try {
      for (const platform of defaultPlatforms) {
        await this.addPlatform(platform);
      }
      console.log('默认平台配置初始化完成');
    } catch (error) {
      console.error('初始化默认平台配置失败:', error);
    }
  }

  /**
   * 获取所有平台配置
   */
  async getPlatforms(): Promise<Platform[]> {
    return new Promise((resolve, reject) => {
      this.db.all('SELECT * FROM platforms', (err, rows) => {
        if (err) {
          console.error('获取平台列表失败:', err.message);
          reject(err);
        } else {
          const platforms = rows.map((row: any) => {
            const typedRow = row as Platform;
            return {
              ...typedRow,
              config: JSON.parse(typedRow.config || '{}')
            };
          });
          console.log(`成功获取 ${platforms.length} 个平台配置`);
          resolve(platforms);
        }
      });
    });
  }

  /**
   * 添加平台配置
   */
  async addPlatform(platform: Platform): Promise<void> {
    return new Promise((resolve, reject) => {
      this.db.run(
        'INSERT OR IGNORE INTO platforms (id, name, displayName, icon, enabled, config) VALUES (?, ?, ?, ?, ?, ?)',
        [platform.id, platform.name, platform.displayName, platform.icon, platform.enabled, JSON.stringify(platform.config)],
        (err) => {
          if (err) {
            console.error('添加平台配置失败:', err.message);
            reject(err);
          } else {
            console.log(`成功添加平台配置: ${platform.displayName} (${platform.id})`);
            resolve();
          }
        }
      );
    });
  }

  /**
   * 删除平台配置
   */
  async removePlatform(platformId: string): Promise<void> {
    return new Promise((resolve, reject) => {
      this.db.run('DELETE FROM platforms WHERE id = ?', [platformId], (err) => {
        if (err) {
          console.error('删除平台配置失败:', err.message);
          reject(err);
        } else {
          console.log(`成功删除平台配置: ${platformId}`);
          resolve();
        }
      });
    });
  }
}
